from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.teacher import Teacher as TeacherModel, TeacherInDB
from app.schemas.teacher import Teacher as TeacherSchema, TeacherCreate, TeacherUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/teachers", tags=["teachers"])

@router.post("/create", response_model=APIResponse[TeacherSchema])
def create_teacher(teacher: TeacherCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating teacher with teacher_no: {teacher.teacher_no}")
    
    # 检查工号是否已存在
    db_teacher = db.query(TeacherModel).filter(TeacherModel.teacher_no == teacher.teacher_no).first()
    if db_teacher:
        logger.warning(f"Teacher already registered with teacher_no: {teacher.teacher_no}")
        return error_response(message="Teacher already registered", code=400)
    
    # 创建新教师
    db_teacher = TeacherModel(
        user_id=teacher.user_id,
        teacher_no=teacher.teacher_no,
        teacher_name=teacher.teacher_name,
        gender=teacher.gender,
        birth_date=teacher.birth_date,
        id_card=teacher.id_card,
        phone=teacher.phone,
        email=teacher.email,
        subject_code=teacher.subject_code,
        job_title=teacher.job_title,
        status=teacher.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_teacher)
    db.commit()
    db.refresh(db_teacher)
    
    # 转换为Pydantic模型
    teacher_response = TeacherInDB.model_validate(db_teacher)
    
    logger.info(f"Teacher created successfully with ID: {db_teacher.id}")
    return success_response(data=teacher_response, message="Teacher created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[TeacherSchema]])
def read_teachers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching teachers with skip: {skip}, limit: {limit}")
    
    teachers = db.query(TeacherModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    teachers_response = [TeacherInDB.model_validate(teacher) for teacher in teachers]
    total = db.query(TeacherModel).count()
    
    logger.info(f"Found {len(teachers)} teachers")
    return paginated_response(
        items=teachers_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{teacher_id}", response_model=APIResponse[TeacherSchema])
def read_teacher(teacher_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching teacher with ID: {teacher_id}")
    
    db_teacher = db.query(TeacherModel).filter(TeacherModel.id == teacher_id).first()
    if db_teacher is None:
        logger.warning(f"Teacher not found with ID: {teacher_id}")
        return error_response(message="Teacher not found", code=404)
    
    # 转换为Pydantic模型
    teacher_response = TeacherInDB.model_validate(db_teacher)
    
    logger.info(f"Teacher found with ID: {teacher_id}")
    return success_response(data=teacher_response)

@router.put("/{teacher_id}", response_model=APIResponse[TeacherSchema])
def update_teacher(teacher_id: int, teacher: TeacherUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating teacher with ID: {teacher_id}")
    
    db_teacher = db.query(TeacherModel).filter(TeacherModel.id == teacher_id).first()
    if db_teacher is None:
        logger.warning(f"Teacher not found with ID: {teacher_id}")
        return error_response(message="Teacher not found", code=404)
    
    # 更新教师信息
    update_data = teacher.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_teacher, key, value)
    
    db_teacher.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_teacher)
    
    # 转换为Pydantic模型
    teacher_response = TeacherInDB.model_validate(db_teacher)
    
    logger.info(f"Teacher updated successfully with ID: {teacher_id}")
    return success_response(data=teacher_response, message="Teacher updated successfully")

@router.delete("/{teacher_id}", response_model=APIResponse[None])
def delete_teacher(teacher_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting teacher with ID: {teacher_id}")
    
    db_teacher = db.query(TeacherModel).filter(TeacherModel.id == teacher_id).first()
    if db_teacher is None:
        logger.warning(f"Teacher not found with ID: {teacher_id}")
        return error_response(message="Teacher not found", code=404)
    
    db.delete(db_teacher)
    db.commit()
    
    logger.info(f"Teacher deleted successfully with ID: {teacher_id}")
    return success_response(message="Teacher deleted successfully")
